<template>
  <div class="health-chart-view">
    <van-tabs v-model:active="activeTab">
      <van-tab title="体重趋势">
        <div class="chart-container">
          <div ref="weightChartRef" class="chart"></div>
        </div>
      </van-tab>
      <van-tab title="血压趋势">
        <div class="chart-container">
          <div ref="bpChartRef" class="chart"></div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { showToast } from 'vant'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { getHealthRecords } from '@/api/health'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart,
  CanvasRenderer
])

const activeTab = ref(0)
const weightChartRef = ref(null)
const bpChartRef = ref(null)
let weightChart = null
let bpChart = null

const initCharts = () => {
  if (weightChartRef.value) {
    weightChart = echarts.init(weightChartRef.value)
  }
  if (bpChartRef.value) {
    bpChart = echarts.init(bpChartRef.value)
  }
  loadData()
}

const loadData = async () => {
  try {
    // 获取体重数据
    const { data: weightData } = await getHealthRecords({ type: 1 })
    if (weightData.length > 0) {
      const dates = weightData.map(r => r.recordTime.substring(5, 10))
      const values = weightData.map(r => parseFloat(r.recordValue))
      updateWeightChart(dates, values)
    }

    // 获取血压数据
    const { data: bpData } = await getHealthRecords({ type: 2 })
    if (bpData.length > 0) {
      const dates = bpData.map(r => r.recordTime.substring(5, 10))
      const values = bpData.map(r => {
        const [systolic, diastolic] = r.recordValue.split('/')
        return [parseInt(systolic), parseInt(diastolic)]
      })
      updateBPChart(dates, values)
    }
  } catch (error) {
    showToast('获取数据失败')
  }
}

const updateWeightChart = (dates, values) => {
  const option = {
    title: {
      text: '体重趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '体重(kg)',
      scale: true
    },
    series: [
      {
        name: '体重',
        type: 'line',
        data: values,
        smooth: true,
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        }
      }
    ]
  }
  weightChart?.setOption(option)
}

const updateBPChart = (dates, values) => {
  const option = {
    title: {
      text: '血压趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['收缩压', '舒张压'],
      top: 30
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      name: 'mmHg',
      scale: true
    },
    series: [
      {
        name: '收缩压',
        type: 'line',
        data: values.map(v => v[0]),
        smooth: true
      },
      {
        name: '舒张压',
        type: 'line',
        data: values.map(v => v[1]),
        smooth: true
      }
    ]
  }
  bpChart?.setOption(option)
}

onMounted(() => {
  initCharts()
  window.addEventListener('resize', () => {
    weightChart?.resize()
    bpChart?.resize()
  })
})

onUnmounted(() => {
  weightChart?.dispose()
  bpChart?.dispose()
  window.removeEventListener('resize', () => {
    weightChart?.resize()
    bpChart?.resize()
  })
})
</script>

<style lang="scss" scoped>
.health-chart-view {
  .chart-container {
    padding: 16px;
    background-color: #fff;
    
    .chart {
      width: 100%;
      height: 300px;
    }
  }
}
</style> 